<template>
    <a-row style="height: 100%">
        <!-- 笔记本栏 -->
        <a-col :span="3" style="background-color: #313640">
            <!-- 头部 -->
            <a-page-header class="ant-page-header-notebook" title="笔记本">
                <template #extra>
                    <!-- 删除笔记本图标 -->
                    <MinusOutlined @click="removeNotebook"
                        style="color: red;cursor: pointer;font-size: 16px;margin-right: 5px;vertical-align: middle;" />
                    <!-- 添加笔记本图标 -->
                    <PlusOutlined @click="showAddNotebookModalForm"
                        style="color: yellow; cursor: pointer; font-size: 16px;vertical-align: middle;" />
                </template>
            </a-page-header>
            <a-divider />
            <!-- 笔记本列表 -->
            <a-menu id="notebook" mode="inline" v-model:selectedKeys="selectedKeys" @select="notebookSelect"
                style="background-color: #313640;max-height: calc(100vh - 200px);min-height: calc(100vh - 200px);overflow: hidden auto;">
                <a-menu-item :key="notebook" v-for="notebook in notebooks">
                    <template #icon>
                        <FolderOpenOutlined />
                    </template>
                    <span>{{ notebook }}</span>
                </a-menu-item>
            </a-menu>
            <!-- 底部同步按钮 -->
            <div click="control-panel"
                style="display: flex; flex-wrap: wrap;flex-direction: column;justify-content: center; align-items: center;padding: 2px 4px;">
                <a-button @click="showSettings"
                    style="width: 105px; margin: 5px 0;font-size: 9px;color: #fff;background-color: #eba227; border-color: #eba227;">
                    <template #icon>
                        <SettingOutlined style="vertical-align: middle;font-size: 9px;" />
                        设&nbsp;&nbsp;&nbsp;&nbsp;置
                    </template>
                </a-button>
                <a-button type="primary" @click="syncToCloud" style="width: 105px; margin: 5px 0;font-size: 9px;">
                    <template #icon>
                        <CloudUploadOutlined style="vertical-align: middle;font-size: 9px;" />
                        同步到云端
                    </template>
                </a-button>
                <a-button @click="downToLocal"
                    style="width: 105px; margin: 5px 0;font-size: 9px;color: #fff;background: #36870e;border-color: #36870e;">
                    <template #icon>
                        <DownloadOutlined style="vertical-align: middle;font-size: 9px;" />
                        同步到本地
                    </template>
                </a-button>
            </div>
        </a-col>

        <!-- 笔记栏 -->
        <a-col :span="5" style="background-color: #f4f5f6">
            <!-- 头部 -->
            <a-page-header title="笔记">
                <template #extra>
                    <!-- 删除笔记图标 -->
                    <MinusOutlined @click="removeNote"
                        style="color: red;cursor: pointer;font-size: 16px;margin-right: 15px;vertical-align: middle;" />
                    <!-- 添加笔记图标 -->
                    <PlusOutlined @click="newNote"
                        style="color: #52c41a; cursor: pointer;font-size: 16px;vertical-align: middle;" />
                </template>
            </a-page-header>
            <a-divider />
            <!-- 笔记列表 -->
            <a-list item-layout="horizontal" :data-source="notes">
                <template #renderItem="{ item }">
                    <a-list-item>
                        <a-list-item-meta @click="noteSelect(item.title)">
                            <template #title>
                                <a>{{ item.title }}</a>
                            </template>
                        </a-list-item-meta>
                    </a-list-item>
                </template>
            </a-list>
        </a-col>

        <!-- 编辑器栏 -->
        <a-col :span="16">
            <div v-if="showMdEditor">
                <a-form layout="inline">
                    <a-form-item style="width: 99.5%; margin: 0 auto; padding: 1px 0">
                        <a-input class="mdtitle-input" v-model:value="mdTitle" placeholder="文章标题"></a-input>
                    </a-form-item>
                </a-form>
                <v-md-editor v-model="mdText" height="94vh" @save="saveMdText"></v-md-editor>
            </div>
        </a-col>
    </a-row>

    <!-- 添加笔记本弹出表单 -->
    <a-modal title="添加笔记本" okText="确认" cancelText="取消" v-model:visible="addNotebookModalFormVisible"
        :confirm-loading="confirmLoading" @ok="addNotebookOk">
        <a-form layout="inline">
            <a-form-item required label="笔记本名称">
                <a-input v-model:value="newNotebookName" placeholder="笔记本名称"></a-input>
            </a-form-item>
        </a-form>
    </a-modal>


    <!-- 设置弹出表单 -->
    <a-modal title="设置" okText="保存" cancelText="取消" v-model:visible="settingsModalFormVisible"
        :confirm-loading="settingsConfirmLoading" @ok="saveSettings">
        <a-form>
            <a-form-item required label="坚果云用户名">
                <a-input v-model:value="jgUserName" placeholder="用户名"></a-input>
            </a-form-item>
            <a-form-item required label="应用名">
                <a-input v-model:value="jgAppName" placeholder="应用名"></a-input>
            </a-form-item>
            <a-form-item required label="应用密码">
                <a-input v-model:value="jgAppPwd" placeholder="应用密码"></a-input>
            </a-form-item>
        </a-form>
    </a-modal>


</template>

<script lang="ts">
    import { defineComponent, reactive, toRefs, onMounted, createVNode } from "vue";
    import { message, Modal } from "ant-design-vue";
    import {
        PlusOutlined,
        MinusOutlined,
        FolderOpenOutlined,
        ExclamationCircleOutlined,
        SettingOutlined,
        CloudUploadOutlined,
        DownloadOutlined,
    } from "@ant-design/icons-vue";

    export default defineComponent({
        components: {
            PlusOutlined,
            MinusOutlined,
            FolderOpenOutlined,
            ExclamationCircleOutlined,
            SettingOutlined,
            CloudUploadOutlined,
            DownloadOutlined,
        },
        setup() {
            const data = reactive({
                notebooks: [], // 笔记本列表
                notes: [], // 笔记列表
                selectedKeys: [], // 笔记本选中项key
                currentNotebook: "", // 当前选中笔记本
                currentNote: "", // 当前选中笔记
                notEditedMdtext: "", // 未编辑的文章内容
                showMdEditor: false, // 是否显示编辑器
                newNotebookName: "", // 新建笔记本的名称
                addNotebookModalFormVisible: false, // 是否显示添加笔记本表单
                confirmLoading: false, // 添加笔记表单等待状态（是否转圈圈）
                settingsModalFormVisible: false, // 设置表单是否显示
                settingsConfirmLoading: false, // 设置表单等待状态
                jgUserName: "", // 坚果云用户名
                jgAppName: "", // 坚果云笔记应用名
                jgAppPwd: "", // 坚果云笔记应用密码
                newNoteMdFileName: "", // 新建的笔记文件名
                mdTitle: "", // 文章标题
                mdText: "", // 文章内容Markdown格式
            });

            // 笔记本被选中
            const notebookSelect = ({ key }) => {
                //   console.log("key", key);

                // 暂存前一个选中的笔记本
                var oldSelectNotebook = data.currentNotebook;

                // 临时创建的笔记且内容为空，在切换到其他笔记本时，直接删除临时笔记
                if (key != oldSelectNotebook && (!data.mdText) && /^\d+$/.test(data.mdTitle)) {
                    window.go.main.App.RemoveTempNote(data.currentNotebook, data.currentNote).then((res) => {
                        if (res && res.code == 200) {
                            data.mdTitle = '';
                            data.mdText = '';
                        }
                    });
                }

                // 判断是否有未保存的文章
                if (
                    key != oldSelectNotebook &&
                    data.mdText &&
                    data.mdText != data.notEditedMdtext
                ) {
                    // 有未保存的文章
                    Modal.confirm({
                        title: () => "编辑器有文章未保存，确认丢弃吗?",
                        icon: () => createVNode(ExclamationCircleOutlined),
                        content: () => "",
                        okText: () => "确认",
                        okType: "danger",
                        cancelText: () => "取消",
                        onOk() {
                            // 点击了确认按钮
                            data.mdText = "";
                            data.showMdEditor = false;
                            data.currentNote = "";
                            message.info("已丢弃", 1);
                        },
                        onCancel() {
                            // 点击了取消按钮
                            data.currentNotebook = oldSelectNotebook;
                            data.selectedKeys = [oldSelectNotebook];
                            message.info("操作取消", 1);
                            return;
                        },
                    });
                }
                data.currentNotebook = key;
                data.currentNote = "";

                // 调用go方法获取笔记本下的全部笔记
                window.go.main.App.GetJGNoteList(key).then((res) => {
                    // console.log(res);
                    if (res && res.code == 200) {
                        var tem = res.data;
                        data.notes = tem.map(n => {
                            return { title: n.replace('.md', '') }
                        });
                    } else {
                        message.error("获取云端数据失败：" + res.msg);
                    }
                });
            };

            // 笔记被选中
            const noteSelect = (noteTitle) => {
                //   console.log("笔记被点击：", noteTitle);
                data.currentNote = noteTitle;
                // 调用go方法读取本地保存的笔记
                window.go.main.App.ReadNoteFile(data.currentNotebook, noteTitle).then(
                    (res) => {
                        //   console.log(res);
                        if (res && res.code == 200) {
                            var tem = res.data;
                            data.mdText = tem;
                            data.notEditedMdtext = tem; // 原始笔记内容
                            data.mdTitle = noteTitle;
                            data.showMdEditor = true;
                        } else {
                            message.error("读取失败：" + res.msg);
                            message.info(`请点击 "同步到本地" 后再打开该笔记`);
                        }
                    }
                );
            };

            // 显示添加笔记本对话框
            const showAddNotebookModalForm = () => {
                data.addNotebookModalFormVisible = true;
            };

            // 添加笔记表本单点击确认按钮
            const addNotebookOk = () => {
                var notebookName = data.newNotebookName.trim();
                data.confirmLoading = true;
                // 创建笔记本
                window.go.main.App.CreateNotebook(notebookName).then((res) => {
                    // console.log(res);
                    if (res && res.code == 200) {
                        message.success("笔记本创建成功", 1);
                        data.notebooks.push(notebookName);
                        data.currentNotebook = notebookName; // 当前笔记本为新建的
                        data.selectedKeys = [notebookName]; // 选中新建的笔记本
                        data.newNotebookName = ""; // 清空
                        data.addNotebookModalFormVisible = false; // 隐藏表单
                    } else {
                        message.error("笔记本创建失败：" + res.msg);
                    }
                    data.confirmLoading = false; // 停止转圈圈
                });
            };

            // 添加笔记
            const newNote = () => {
                var notebook = data.currentNotebook;
                if (notebook) {
                    window.go.main.App.CreateNoteFile(notebook).then((res) => {
                        if (res && res.code == 200) {
                            message.success("笔记创建成功：" + fileName, 1);
                            var fileName = res.data;
                            data.newNoteMdFileName = fileName;
                            data.notes.push({ title: fileName });
                            data.currentNote = fileName;    // 置当前笔记为新建的临时笔记
                            // 打开该临时笔记
                            data.mdTitle = fileName;
                            data.mdText = '';
                            data.showMdEditor = true;
                        } else {
                            message.error("笔记创建失败：" + res.msg);
                        }
                    });
                }
            };

            // 保存文章/笔记
            const saveMdText = (MdText) => {
                // console.log(MdText);
                if (!data.mdTitle) {    // 标题为空
                    message.info('请输入标题', 2);
                    return;
                }
                if (/^\d+$/.test(data.mdTitle)) {   // 标题为临时文件名
                    message.info('请输入新标题', 2);
                    return;
                }
                if (data.currentNotebook && data.currentNote) { // 不为空
                    // 调用go方法保存笔记
                    window.go.main.App.SaveNote(data.currentNotebook, data.newNoteMdFileName, data.mdTitle, MdText).then((res) => {
                        if (res && res.code == 200) {
                            message.success("笔记保存成功", 1);
                            // 重新获取笔记列表
                            window.go.main.App.GetJGNoteList(data.currentNotebook).then((res) => {
                                if (res && res.code == 200) {
                                    var tem = res.data;
                                    data.notes = tem.map(n => {
                                        return { title: n.replace('.md', '') }
                                    });
                                } else {
                                    message.error('获取笔记列表失败：' + res.msg);
                                }
                            });

                        } else {
                            message.error('笔记保存失败：' + res.msg);
                        }
                    });
                } else {  // 存在为空情况
                    message.error('请选定笔记本和笔记');
                }
            }

            // 删除笔记本
            const removeNotebook = () => {
                if (data.currentNotebook) {
                    Modal.confirm({
                        title: () => `确认删除笔记本 "${data.currentNotebook}" 吗？`,
                        content: () => '删除笔记本，其中的笔记文件也将一并删除！',
                        icon: () => createVNode(ExclamationCircleOutlined),
                        okText: () => '删除',
                        okType: 'danger',
                        cancelText: () => '取消',
                        onOk() {
                            // 点击了确定，开始删除
                            window.go.main.App.RemoveNotebook(data.currentNotebook).then((res) => {
                                if (res && res.code == 200) {
                                    // 从坚果云获取笔记本数据
                                    window.go.main.App.GetJGNotebook().then((res) => {
                                        if (res && res.code == 200) {
                                            data.notebooks = res.data;
                                        } else {
                                            message.error("获取云端数据失败：" + res.msg);
                                        }
                                    });
                                    // 当前笔记本置空
                                    data.currentNotebook = '';
                                    message.success('删除成功', 1);
                                } else {
                                    message.error('删除失败：' + res.msg);
                                }
                            });
                        },
                        onCancel() {
                            message.info('取消操作', 1);
                        },
                    });
                } else {
                    message.info('请选中要删除的笔记本', 1);
                }
            }

            // 删除笔记
            const removeNote = () => {
                if (data.currentNotebook == '' || data.currentNote == '') {
                    message.error('请选择笔记');
                    return;
                }
                Modal.confirm({
                    title: () => `确认删除笔记 "${data.currentNotebook} \ ${data.currentNote}" 吗？`,
                    icon: () => createVNode(ExclamationCircleOutlined),
                    okText: () => '删除',
                    okType: 'danger',
                    cancelText: () => '取消',
                    onOk() {
                        // 点击了确定，开始删除
                        window.go.main.App.RemoveNote(data.currentNotebook, data.currentNote).then((res) => {
                            if (res && res.code == 200) {
                                // 重新获取笔记列表
                                window.go.main.App.GetJGNoteList(data.currentNotebook).then((res) => {
                                    if (res && res.code == 200) {
                                        var tem = res.data;
                                        data.notes = tem.map(n => {
                                            return { title: n.replace('.md', '') }
                                        });
                                        // console.log('重新获取笔记列表函数已调用');
                                    } else {
                                        message.error("获取云端数据失败：" + res.msg);
                                    }
                                });
                                // 当前笔记置空
                                data.currentNote = "";
                                data.mdTitle = '';
                                data.mdText = '';
                                message.success('删除成功', 1);
                            } else {
                                message.error('删除失败：' + res.msg);
                            }
                        });
                    },
                    onCancel() {
                        message.info('取消操作', 1);
                    },
                });
            }

            // 显示设置表单
            const showSettings = () => {
                data.settingsModalFormVisible = true;
            }

            // 保存设置
            const saveSettings = () => {
                data.settingsConfirmLoading = true; // 开始转圈圈
                let username = data.jgUserName.trim();
                let appname = data.jgAppName.trim();
                let apppwd = data.jgAppPwd.trim();
                if (username == "" || appname == "" || apppwd == "") {
                    data.settingsConfirmLoading = false; // 停止转圈圈
                    message.error("请填写完整");
                    return;
                }

                // 调用go端进行保存设置
                window.go.main.App.SaveSettings(username, appname, apppwd).then((res) => {
                    if (res && res.code == 200) {
                        message.success('设置成功，重启生效！', 3);
                        // 清空
                        data.jgUserName = '';
                        data.jgAppName = '';
                        data.jgAppPwd = '';
                        data.settingsModalFormVisible = false;  // 隐藏表单
                    } else {
                        message.error('设置失败：' + res.msg, 3);
                    }
                    data.settingsConfirmLoading = false; // 停止转圈圈
                });

            }


            // 同步到云端
            const syncToCloud = () => {
                message.info('开始同步');
                window.go.main.App.SyncToCloud().then((res) => {
                    if (res && res.code == 200) {
                        message.success('同步成功', 1);
                    } else {
                        message.error('同步失败：' + res.msg);
                    }
                });
            }

            // 同步到本地
            const downToLocal = () => {
                message.info('开始同步');
                window.go.main.App.DownToLocal().then((res) => {
                    if (res && res.code == 200) {
                        message.success('同步成功', 1);
                    } else {
                        message.error('同步失败：' + res.msg);
                    }
                });
            }

            // 生命周期，挂载完毕
            onMounted(() => {
                // 从坚果云获取笔记本数据
                window.go.main.App.GetJGNotebook().then((res) => {
                    // console.log(res);
                    if (res && res.code == 200) {
                        data.notebooks = res.data;
                    } else {
                        message.error("获取云端数据失败：" + res.msg);
                    }
                });
            });

            return {
                ...toRefs(data),
                notebookSelect,
                noteSelect,
                showAddNotebookModalForm,
                addNotebookOk,
                newNote,
                saveMdText,
                removeNotebook,
                removeNote,
                showSettings,
                saveSettings,
                syncToCloud,
                downToLocal,
            };
        },
    });
</script>

<style>
    .ant-page-header-notebook {
        padding: 16px 18px !important;
    }

    .ant-page-header-heading-left {
        margin: 0 !important;
    }

    .ant-page-header-heading-title {
        color: #1890ff !important;
    }

    .ant-divider-horizontal {
        margin: 0 !important;
    }

    #notebook {
        border: none !important;
    }

    .ant-menu-title-content {
        color: white !important;
        /* padding: 0 15px !important; */
        font-weight: 500 !important;
    }

    .ant-menu:not(.ant-menu-horizontal) .ant-menu-item-selected {
        background-color: #49565c !important;
    }


    /* 控制面板 */
    .control-panel .ant-btn-icon-only {
        width: unset !important;
        height: unset !important;
        padding: 0 !important;
    }

    .ant-list-item-meta {
        cursor: pointer;
    }

    .ant-list-item-meta:hover {
        background-color: #ccc;
    }

    .ant-list-item-meta-content {
        cursor: pointer;
    }

    .ant-list-item-meta-content:hover {
        background-color: #ccc;
    }

    .ant-list-item {
        padding: 6px 0 !important;
    }

    .ant-list-item-meta-title {
        margin-bottom: 0 !important;
        padding: 0 5px !important;
        font-size: 15px !important;
    }

    .ant-list-item-meta-title a {
        vertical-align: middle !important;
    }

    .ant-list-items {
        overflow: hidden auto !important;
        max-height: calc(100vh - 80px) !important;
        min-height: calc(100vh - 80px) !important;
    }

    .mdtitle-input {
        border: 1px solid !important;
        border-top: none !important;
        border-left: none !important;
        border-right: none !important;
        border-bottom-color: blueviolet !important;
    }
</style>